const ObjectID = require('mongodb').ObjectID;
const qrcode = require('yi-wx-qrcode');
const sensitiveWords = require('yi-sensitive-words');
const qiniu = require('yi-qiniu');
const fs = require('fs');

const middleware = (req, res, next) => {
    sensitiveWords(req.body.title, function (r) {
        if (r.length > 0) {
            return res.reply({"code": 1500, "errMsg": "卡片发布失败！卡片内容包含敏感词"})
        }
        next();
    });
};

module.exports = {
    open:false,
    description: '新增卡片',
    middleware: middleware,
    handler(req, res, next) {
        let doc = req.body;
        let longitude = doc.longitude;
        let latitude = doc.latitude;
        let lnglat = [];
        if (longitude && latitude) {
            lnglat = [longitude, latitude];//将经度和纬度合成经纬度数组,此处切记顺序，经度在前，纬度在后，不可调换
        }
        delete doc.latitude;
        delete doc.longitude;
        doc.lnglat = lnglat;
        let id = new ObjectID();
        doc._id = id;
        doc.createTime = new Date();
        let qrcodePath = __dirname + "/qrCode_" + id.toString() + ".jpg";
        let qrcodeData = qrcode(
            req.config.miniprogram.appid,
            req.config.miniprogram.appsecret,
            "pages/carddetails/carddetails",
            id.toString(),
            qrcodePath,
            () => {
                if (!fs.existsSync(qrcodePath))
                    return res.reply({code: 1501, message: '小程序二维码生成失败！'})
                qiniu.uploadfile(qrcodePath, "qrCode_" + id.toString() + ".jpg", (e1, r1) => {

                    if (e1) {
                        return res.reply({code: 1502, message: '上传二维码失败'})

                        // doc.qrcodePath = 'http://sl.huiwanvip.com/5e20192e19e6ef584f78aad2/content.png';
                        // req.mongo.collection("card").insertOne(doc,(e,r)=>{
                        //     if (e) return res.err.mongoError(e);
                        //     let obj = new Object();
                        //     obj._id = r.insertedId;//将返回值中的insertedId属性赋给obj中新添加的属性_id
                        //     return res.reply({code:0,message:'发布成功',data:obj});
                        // });
                    } else {
                        doc.qrcodePath = r1.url;
                        fs.unlinkSync(__dirname + "/qrCode_" + id.toString() + ".jpg");
                        req.mongo.collection("card").insertOne(doc, (e, r) => {
                            if (e) return res.err.mongoError(e);
                            let obj = new Object();
                            obj._id = r.insertedId;//将返回值中的insertedId属性赋给obj中新添加的属性_id
                            return res.reply({code: 0, message: '发布成功', data: obj})
                        });
                    }
                });
            }
        );
    }
};
